let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class 营业部Controller extends BaseController {
    constructor() {
        super();
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/09字典/券商/营业部/`
        this.companyCodeArr = [];
        this.companyCodeIndex = 0;
    }
    /**
     * 获取url
     * @param date 证券公司code
     */
    getUrl(date) {
        return `http://data.eastmoney.com/DataCenter_V3/stock2016/yybSearch.ashx?pagesize=50&page=1&js=var%20RnfpeEwA&param=&sortRule=-1&sortType=UpCount&typeCode=1&gpfw=0&code=${date}&rt=25550104`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('38营业部Controller')
        console.log(this.companyCodeIndex)
        if (!this.companyCodeArr[this.companyCodeIndex]) return false;
        let data = await this.getData(this.companyCodeArr[this.companyCodeIndex], this.isCache)
        this.data = this.axiosDataFormat(data.toString());
        this.writeCsv(this.data);
        this.companyCodeIndex++
        await this.getHistory()
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        return JSON.parse(data.replace('var RnfpeEwA=', '')).data
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        this.file = `营业部_${this.companyCodeArr[this.companyCodeIndex]}_${new Date().format('yyyyMMdd')}.csv`
        fs.writeFileSync(path.join(this.baseSrc, this.file), this.convertToCSV(arr, 'title'), 'UTF-8')

    }

    readDataSuorce() {
        let data = fs.readFileSync(`d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/09字典/券商/证券公司/证券公司数据_${new Date().format('yyyyMMdd')}.csv`);
        data.toString().split(/\n/g).map(item => {
            if (item.split(',')[0] !== '证券公司ID') {
                this.companyCodeArr.push(item.split(',')[0])
            }
        })
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.isCache = isCache;
        console.log('--->38营业部Controller')
        this.readDataSuorce()
        await this.getHistory()
    }
}

let controller = new 营业部Controller()
module.exports = controller
